/** @format */

import { computed, ref } from 'vue'
import { UserService } from '../services/userService'
import { formatDateYMDHMS, sortByDesc } from '../utils/commonUtils'
import { useEntity } from './useEntity'

const userService = new UserService()
const openId = ref()
const DEF_USER_KEY = 'user1'

const getOpenId = async () => {
  openId.value = await userService.getOpenId()
}

let p: any = null
const getOpenIdOnce = async () => {
  if (!p) p = getOpenId()
  return await p
}

export const useRedFlower = (params = {}) => {
  // 用户
  const userOpts = {
    path: async () => {
      // 否则取得用户信息
      await getOpenIdOnce()
      return `flowers/${openId.value}/users`
    },
  }
  const {
    content: userContent,
    getData: getUser,
    updateData: updateUser,
  } = useEntity(userOpts)
  // 用户列表
  const users = computed(() => {
    if (userContent.value?.list?.length) {
      return userContent.value.list
    }
    return [{ key: DEF_USER_KEY, name: '用户1' }]
  })
  // 当前用户
  const currentUser = ref()

  const makeFilePath = async (userKey, key) => {
    // 否则取得用户信息
    await getOpenIdOnce()
    return `flowers/${openId.value}/${userKey}/${key}`
  }

  // 增加记录
  const options = {
    pathUpdate: async (params) => makeFilePath(params, 'amounts'),
    path: async () => makeFilePath(DEF_USER_KEY, 'amounts'),
  }
  const { content, getData, updateData } = useEntity(options)

  // 使用记录
  const useOpts = {
    pathUpdate: async (params) => makeFilePath(params, 'logs'),
    path: async () => makeFilePath(DEF_USER_KEY, 'logs'),
  }
  const {
    content: useContent,
    getData: getUse,
    updateData: updateUse,
  } = useEntity(useOpts)

  const useLogs = computed(() => {
    const keys = sortByDesc(Object.keys(useContent.value))

    const list = keys.map((key) => {
      let tmp = useContent.value[key].list
      return tmp
    })
    return list.flat().map((item) => {
      const { date, ...rest } = item
      rest.date = formatDateYMDHMS(item.date)
      return rest
    })
  })

  const queryData = async () => {
    await getUser()
  }

  // 切换用户
  const switchUser = async (user) => {
    // 相同是时，不需要切换
    if (user.key === currentUser.value?.key) return
    currentUser.value = user

    await Promise.all([
      getData(user.key, { update: true }),
      getUse(user.key, { update: true }),
    ])
  }

  // 增加用户
  const addUser = async (userName) => {
    // 增加用户
    const newUser = {
      key: `user${users.value.length + 1}`,
      name: userName,
    }
    await updateUser({ list: users.value.concat(newUser) })

    return newUser
  }

  // 修改用户信息
  const changeUser = async (user) => {
    // 找到用户列表中的当前用户
    const index = users.value.findIndex((u) => u.key === user.key)
    if (index !== -1) {
      users.value[index] = user
      await updateUser({ list: users.value })
    }
  }

  return {
    currentUser,
    users,
    addUser,
    changeUser,
    switchUser,

    content,
    useContent,
    useLogs,
    queryData,
    updateAmount: updateData,
    updateUse,
  }
}
